<template>
  <div id="picture">
    <el-button @click="toUpload" type="primary" class="upload">上传图片</el-button>

    <el-table
                :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
                style="width: 100%"
                border
                >
          <el-table-column
                  prop="picture"
                  label="图片"
                  align="center"
                  >
            <template slot-scope="scope">
                <el-image
                        style="width: 150px; height: 100px"
                        :src="scope.row.picture"
                        fit="contain">
                </el-image>
            </template>
          </el-table-column>
          <el-table-column
                  prop="owner"
                  label="拥有者"
                  align="center"
          >
          </el-table-column>
          <el-table-column
                  prop="value"
                  label="金额"
                  align="center"
          >
          </el-table-column>
        <el-table-column
                label="拥有权/转载权"
                align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.illegal === 0">
              <el-button v-if="scope.row.owner === user" type="info" disabled>已拥有</el-button>
              <el-button v-else type="primary" @click="getOwner(scope.row.value,scope.row.owner,scope.row.picture)">购买</el-button>
              <el-button v-if="scope.row.reprint == 1" type="info" disabled>已有转载权</el-button>
              <el-button type="primary" v-else @click="toReprint(scope.row.value,scope.row.owner,scope.row.picture,scope.row.imghash)">获取</el-button>
            </div>
            <div v-else>
              该图片已侵权
            </div>
          </template>
        </el-table-column>
          <el-table-column
                  label="操作"
                  align="center">
            <template slot-scope="scope">
              <el-button type="primary" @click="toDetail(scope.row.imghash)">详情</el-button>
            </template>

          </el-table-column>
        </el-table>
    <div class="block">
      <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[2,4,6]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.length">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import Layout from "../../components/layout/Layout";
  export default {
    name: "Picture",
    data() {
      return {
        tableData: [],
        file:{name:'',url:""},
        pageSize:4,
        currentPage:1,
        uploadUrl : "",
        user : ""
      }
    },
    components:{
      Layout
    },
    created() {
      this.user = this.$store.getters.getSender
      this.init()
    },
    methods: {
      async init(){
        await this.getAllImg()
        for (let item of this.tableData)
        {
          await this.getReprint(item.imghash)
        }
      },
      async getAllImg(){
         await this.$http.get('api/getAllImg').then((res) => {
          let result = res.data.data
          this.tableData = []
          for(let per of result)
          {

            let perPicture = {}
            perPicture.picture = per.img_info.imgurl;
            perPicture.value = per.amount
            perPicture.owner = per.sender
            perPicture.isOwner = per.img_info.isOwner
            perPicture.illegal = per.img_info.illegal
            perPicture.imghash = per.img_info.imghash
            perPicture.reptint = false
            this.tableData.push(perPicture)
          }
        }).catch(err => {
          console.log(err)
        })
      },
      //根据图片url与sender判断sender是否拥有转载权
       async getReprint(imgHash){
         await this.$http.get('api/getImgReprinterList?imghash='+imgHash)
            .then(res => {
              let result = res.data.data
              let reprint = result.some(item => {
                return item.sender == this.user
              })
              for(let i in this.tableData)
              {
                if(this.tableData[i].imghash == imgHash){
                  this.tableData[i].reprint = reprint
                }
              }
            })
         this.$forceUpdate()
      },

      //获取转载权
      toReprint(amount,receiver,imgUrl,imgHash){
        // this.$router.push('/pictureIndex/reprint')
        this.$prompt( `获取转载权最低价格为：${amount * 0.2} 元` , '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator(value){
            if(value >= 10)return true
            else return "输入金钱不够获取转载权"
          }
        }).then(({ value }) => {
          this.$message({
            type: 'success',
            message: `你输入金钱为: ${value} 元`
          })

        //  发送转载信息
          let form = {}
          form.sender = this.$store.getters.getSender
          form.receiver = receiver
          form.amount = value
          form.img_url = imgUrl
          this.$http.post('api/pay/image',form)
              .then(res =>{
                // console.log(res)
                this.getReprint(imgHash)
              })
              .catch(err => {
                console.log(err)
              })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },

      //购买图片
      getOwner(amount,receiver,imgUrl){
        this.$prompt(
            `当前图片价格为：${amount} 元`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator(value){
            if(value > amount)return true
            else return "输入金钱不能购买"
          },
        }).then(({ value }) => {
          this.$message({
            type: 'success',
            message: `你输入金钱为: ${value} 元`
          });
          let form = {}
          form.sender = this.$store.getters.getSender
          form.receiver = receiver
          form.amount = value
          form.img_url = imgUrl
          this.$http.post('api/pay/image',form)
          .then(res =>{
            console.log(res)
            this.getAllImg()
          })
          .catch(err => {
            console.log(err)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },

      //跳转到详情
      toDetail(imgHash){
        this.$router.push({
          path:"/pictureIndex/detail",
          query:{
            imgHash
          }
        })
      },

      //跳转到上传图片组件
      toUpload(){
        this.$router.push('/pictureIndex/upload')
      },

      //分页
      handleSizeChange(val) {
        this.pageSize = val
      },
      handleCurrentChange(val) {
        this.currentPage = val
      }
    },
  }
</script>

<style scoped>
  #picture{
    text-align: right;
  }
  .el-aside {
    background-color: #D3DCE6;
    color: #333;
    text-align: center;
    height: 100vh;
    line-height:100vh;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
    text-align: center;
    height: 100vh;
    line-height: 100vh;
  }
  .el-table{
    border: 1px solid #e0dede;
    text-align: center;
  }
  .el-table-column{
    text-align: center;
  }
  .upload{
    margin-bottom: 20px;
    margin-right: 100px;
  }
</style>